package com.fdb.efp.console.api.rest;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import com.fdb.basic.framework.core.constant.PubConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fdb.efp.console.common.ConsoleConstant;
import com.fdb.efp.console.service.facade.PubSysInfoService;
import com.fdb.efp.console.service.facade.SOrgLimitService;
import com.fdb.efp.console.service.vo.SOrgLimitVO;
import com.fdb.efp.console.service.facade.SRoleDataRuleService;
import com.fdb.basic.framework.core.constant.BaseConstant;
import com.fdb.basic.framework.core.constant.DataRuleType;
import com.fdb.basic.framework.core.constant.ResponseData;
import com.fdb.basic.framework.core.util.TimeUtil;
import com.fdb.basic.framework.core.util.UUIDUtil;
import com.fdb.basic.framework.web.controller.AbstractController;

@RestController
@RequestMapping("/api")
public class SOrgLimitController extends AbstractController {

	@Autowired
	@Qualifier("sOrgLimitService")
	private SOrgLimitService sOrgLimitService;

	@Autowired
	@Qualifier("pubSysInfoService")
	private PubSysInfoService pubSysInfoService;
	@Autowired
	@Qualifier("sRoleDataRuleService")
	private SRoleDataRuleService sRoleDataRuleService;

	/**
	 * 列表数据查询
	 * 
	 * @param page
	 * @param size
	 * @return
	 */
	@RequestMapping(value = "/s/org/limits", method = RequestMethod.POST)
	public @ResponseBody ResponseData<List<SOrgLimitVO>> querySOrgLimitAll(@RequestBody SOrgLimitVO vo) {
		setUserInfoToVO(vo);
		if (vo.getOrgLimitDate() != null && vo.getOrgLimitDate().length == 2 && vo.getOrgLimitDate()[0] != null) {
			vo.setOrgLimitStartDate(vo.getOrgLimitDate()[0]);
			vo.setOrgLimitEndDate(vo.getOrgLimitDate()[1]);
		}

		// 根据用户角色获取用户权限方案
		List<SOrgLimitVO> outputVo = null;
		Map<String,String> dataRuleTypeMap = sRoleDataRuleService.getDataRuleType(httpRequest.getRequestURI(), getUserRoles());
		vo.setPrdCodebyBaseInfo(dataRuleTypeMap == null ? null:dataRuleTypeMap.get(PubConstant.PRD_CODE));
		DataRuleType dataRuleType = DataRuleType.getDataRuleType(dataRuleTypeMap == null ? null:dataRuleTypeMap.get(PubConstant.PERMIS_TYPE));
		setUserInfoToVO(vo);
		// 根据权限方案调用不同的方案进行数据查询
		switch (dataRuleType) {
		case Owner:
			outputVo = sOrgLimitService.queryAllOwner(vo);
			break;
		case CurrOrg:
			outputVo = sOrgLimitService.queryAllCurrOrg(vo);
			break;
		case CurrDownOrg:
			outputVo = sOrgLimitService.queryAllCurrDownOrg(vo);
			break;
		default:
			outputVo = sOrgLimitService.queryAllOwner(vo);
			break;
		}
		return getResponseData(outputVo);

	}

	/**
	 * 根据主键查询详情
	 * 
	 * @return
	 */
	@RequestMapping(value = "/s/org/limit/{legalOrgCode}", method = RequestMethod.GET)
	public @ResponseBody ResponseData<SOrgLimitVO> queryByPk(@PathVariable("id") String id) {

		SOrgLimitVO inVo = new SOrgLimitVO();
		inVo.setId(id);
		setUserInfoToVO(inVo);
		SOrgLimitVO outputVo = sOrgLimitService.queryByPk(inVo);
		return getResponseData(outputVo);
	}

	/**
	 * 根据主键删除信息
	 * 
	 * @param sOrgLimit
	 * @return
	 */
	@RequestMapping(value = "/s/org/limit", method = RequestMethod.DELETE)
	public @ResponseBody ResponseData<Integer> deleteByPk(@RequestBody SOrgLimitVO inSOrgLimitVo) {
		setUserInfoToVO(inSOrgLimitVo);
		if (!inSOrgLimitVo.getLoginUserOrgCode().equals(inSOrgLimitVo.getCreateOrgCode())) {// 创建机构非登录机构，不允许删除
			ResponseData<Integer> responseData = new ResponseData<>();
			return responseData.fail("删除权限不足，删除失败!");
		}
		int outputVo = sOrgLimitService.deleteByPk(inSOrgLimitVo);
		return getResponseData(outputVo);
	}

	/**
	 * 处理审批通过
	 * 
	 * @param inSOrgLimitVo
	 * @return
	 */
	@RequestMapping(value = "/s/org/limit/agree", method = RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> apprAgree(@RequestBody SOrgLimitVO inSOrgLimitVo) {
		if (BaseConstant.APPR_STATUS_111.equals(inSOrgLimitVo.getApproveStatus())) {
			String openDay = pubSysInfoService.getOpenday(BaseConstant.SYS_ID_1001);// 20180718
			inSOrgLimitVo.setAprvUserCode(inSOrgLimitVo.getLoginUserId());
			inSOrgLimitVo.setApproveStatus(BaseConstant.APPR_STATUS_997);// 同意
			inSOrgLimitVo.setAprvDate(openDay);
			inSOrgLimitVo.setLastUpdateTime(TimeUtil.getCurrentDateTime());
			inSOrgLimitVo.setLastUpdateUser(inSOrgLimitVo.getLoginUserId());
			if (inSOrgLimitVo.getCreateUser().equals(inSOrgLimitVo.getAprvUserCode())) {// 审批人不能是创建人
				ResponseData<Integer> responseData = new ResponseData<>();
				return responseData.fail("创建人不能审批!");
			}
			int outputVo = sOrgLimitService.updateByPk(inSOrgLimitVo);
			return getResponseData(outputVo);
			/** 【注释】
			 * try {
				int b = TimeUtil.compareDates(openDay, inSOrgLimitVo.getOrgLimitStartDate());
				int e = TimeUtil.compareDates(openDay, inSOrgLimitVo.getOrgLimitEndDate());

				logger.info(inSOrgLimitVo.getLegalOrgCode()+"机构限额开始时间和营业时间比较 b="+b+",e="+e);
				if (b >= 0 && e <= 0) {
					// 变成生效状态
					inSOrgLimitVo.setOrgLimitSts(ConsoleConstant.COMMON_STATUS_1);//生效
				}else {
					inSOrgLimitVo.setOrgLimitSts(ConsoleConstant.COMMON_STATUS_0);//待生效
				}
				int outputVo = sOrgLimitService.updateByPk(inSOrgLimitVo);
				return getResponseData(outputVo);
			}catch (Exception e) {
				ResponseData<Integer> responseData = new ResponseData<>();
				return responseData.fail( "机构额度生效审批出错!");
			}*/

		} else {
			ResponseData<Integer> responseData = new ResponseData<>();
			return responseData.fail("非审批中状态不允许审批!");
		}
	}

	/**
	 * 处理审批否决
	 * 
	 * @param inSOrgLimitVo
	 * @return
	 */
	@RequestMapping(value = "/s/org/limit/vote", method = RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> apprVote(@RequestBody SOrgLimitVO inSOrgLimitVo) {
		if (BaseConstant.APPR_STATUS_111.equals(inSOrgLimitVo.getApproveStatus())) {
			if (inSOrgLimitVo.getCreateUser().equals(inSOrgLimitVo.getLoginUserId())) {// 审批人不能是创建人
				ResponseData<Integer> responseData = new ResponseData<>();
				return responseData.fail("创建人不能审批!");
			}
			inSOrgLimitVo.setApproveStatus(BaseConstant.APPR_STATUS_998);// 否决
			int outputVo = sOrgLimitService.updateByPk(inSOrgLimitVo);
			return getResponseData(outputVo);
		} else {
			ResponseData<Integer> responseData = new ResponseData<>();
			return responseData.fail("非审批中状态不允许审批!");
		}
	}

	/**
	 * 根据主键更新信息
	 * 
	 * @param inSOrgLimitVo
	 * @return
	 */
	@RequestMapping(value = "/s/org/limit", method = RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateByPk(@RequestBody SOrgLimitVO inSOrgLimitVo) {
		setUserInfoToVO(inSOrgLimitVo);

		inSOrgLimitVo.setLastUpdateTime(TimeUtil.getCurrentDateTime());
		inSOrgLimitVo.setLastUpdateUser(inSOrgLimitVo.getLoginUserId());

		/**【注释】
		 * if(ConsoleConstant.APPROVE_STATUS_998.equals(inSOrgLimitVo.getApproveStatus())) {
			ResponseData<Integer> responseData = new ResponseData<>();
			return responseData.fail( "审批未通过，限额失败！");
		}*/

		List<SOrgLimitVO> list = sOrgLimitService.checkStateQuery(inSOrgLimitVo);
		if (!list.isEmpty()) {
			if (list.size() > 2) {
				ResponseData<Integer> responseData = new ResponseData<>();
				return responseData.fail("修改后的机构在该时间段已经存在了记录，修改失败！");
			} else if (list.size() == 2) {
				if (!list.get(0).getId().equals(inSOrgLimitVo.getId()) && !list.get(1).getId().equals(inSOrgLimitVo.getId())) {
					ResponseData<Integer> responseData = new ResponseData<>();
					return responseData.fail("修改后的机构在该时间段已经存在了记录，修改失败！");
				} else if (list.get(0).getId().equals(inSOrgLimitVo.getId())) {
					// 修改的是第一条记录

				} else if (list.get(1).getId().equals(inSOrgLimitVo.getId())) {
					// 修改的是第二条记录

				}
			} else if (list.size() == 1) {

			}
		}

		if (!ConsoleConstant.FIRST_LEGALORGCODE.equals(inSOrgLimitVo.getLegalOrgCode())) {
			// 查检额度设置
			List<SOrgLimitVO> orgLegal = sOrgLimitService.checkLimitAmtQuery(inSOrgLimitVo);

			if (orgLegal != null && !orgLegal.isEmpty()) {
				BigDecimal amt = orgLegal.get(0).getOrgLimitAmt();
				// 判断 金额不能超过省的

				if (inSOrgLimitVo.getOrgLimitAmt().compareTo(amt) > 0) {
					ResponseData<Integer> responseData = new ResponseData<>();
					return responseData.fail("修改后的机构的额度超过了省联社设置的额度，请重新设置额度！");
				}
			}
		}
		int outputVo = sOrgLimitService.updateByPk(inSOrgLimitVo);
		return getResponseData(outputVo);

	}

	/**
	 * 根据主键更新信息
	 * 
	 * @param inSOrgLimitVo
	 * @return
	 */
	@RequestMapping(value = "/s/org/updateState", method = RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateStateByPk(@RequestBody SOrgLimitVO inSOrgLimitVo) {
		setUserInfoToVO(inSOrgLimitVo);
		inSOrgLimitVo.setLastUpdateTime(TimeUtil.getCurrentDateTime());
		inSOrgLimitVo.setLastUpdateUser(inSOrgLimitVo.getLoginUserId());
		int outputVo = sOrgLimitService.updateStateByPk(inSOrgLimitVo);
		return getResponseData(outputVo);

	}

	/**
	 * 新增数据
	 * 
	 * @param inSOrgLimitVo
	 * @return
	 */
	@RequestMapping(value = "/s/org/limit", method = RequestMethod.POST)
	public @ResponseBody ResponseData<Integer> insertSOrgLimit(@RequestBody SOrgLimitVO inSOrgLimitVo) {

		List<SOrgLimitVO> list = sOrgLimitService.checkStateQuery(inSOrgLimitVo);
		if (!list.isEmpty()) {
			if (list.size() == 1) {
				if (!ConsoleConstant.FIRST_LEGALORGCODE.equals(list.get(0).getCreateOrgCode())) {// 不省联社创建,允许法人机构创建
					if (!ConsoleConstant.FIRST_LEGALORGCODE.equals(inSOrgLimitVo.getCreateOrgCode())) {// 创建者是省联社
						ResponseData<Integer> responseData = new ResponseData<>();
						return responseData.fail("新增的机构在该时间段已经存在了记录，请先删除再新增！");
					}
				} else if (ConsoleConstant.FIRST_LEGALORGCODE.equals(inSOrgLimitVo.getCreateOrgCode())) {// 省联社创建,不允许省联社再次创建
					if (ConsoleConstant.FIRST_LEGALORGCODE.equals(inSOrgLimitVo.getCreateOrgCode())) {// 创建者是省联社
						ResponseData<Integer> responseData = new ResponseData<>();
						return responseData.fail("新增的机构在该时间段已经存在了记录，请先删除再新增！");
					}
				}
			} else {
				ResponseData<Integer> responseData = new ResponseData<>();
				return responseData.fail("新增的机构在该时间段已经存在了记录，请先删除再新增！");
			}
		}
		if (!ConsoleConstant.FIRST_LEGALORGCODE.equals(inSOrgLimitVo.getLegalOrgCode())) {
			// 查检额度设置
			List<SOrgLimitVO> orgLegal = sOrgLimitService.checkLimitAmtQuery(inSOrgLimitVo);
			if (orgLegal != null && !orgLegal.isEmpty()) {
				BigDecimal amt = orgLegal.get(0).getOrgLimitAmt();
				// 判断 金额不能超过省的
				if (inSOrgLimitVo.getOrgLimitAmt().compareTo(amt) > 0) {
					ResponseData<Integer> responseData = new ResponseData<>();
					return responseData.fail("新增的机构的额度超过了省联社设置的额度，请重新设置额度！");
				}
			}
		}
		setUserInfoToVO(inSOrgLimitVo);
		inSOrgLimitVo.setId(UUIDUtil.getUUID());
		inSOrgLimitVo.setCreateTime(TimeUtil.getCurrentDateTime());
		inSOrgLimitVo.setCreateUser(inSOrgLimitVo.getLoginUserId());
		int outputVo = sOrgLimitService.insertSOrgLimit(inSOrgLimitVo);
		return getResponseData(outputVo);

	}
}
